from datetime import timedelta

from odoo import api, fields, models
from odoo.exceptions import UserError


class RpFestival(models.Model):
    _name = 'rp.festival'
    _description = '节日表'
    _sql_constraints = [('name_unique', 'UNIQUE(name)', '节日名称需要唯一')]

    name = fields.Char(string='名称', copy=False)
    start_date = fields.Date(string='开始时间', copy=False, required=True)
    end_date = fields.Date(string='结束时间', copy=False, required=True)
    extend_upwards = fields.Integer(string='向上延长时间', copy=False)
    extend_downwards = fields.Integer(string='向下延长时间', copy=False)
    actual_begin_date = fields.Date(string='实际开始时间', copy=False)
    actual_end_date = fields.Date(string='实际结束时间', copy=False)

    @api.constrains('start_date', 'end_date', 'extend_upwards', 'extend_upwards')
    def constraint_on_value(self):
        for record in self:
            # 有效期限判断
            if (record.end_date - record.start_date).days < 0 or record.end_date < fields.date.today():
                raise UserError('请填写有效时间！')
            # 延长时间判断
            if all([record.extend_upwards, record.extend_downwards]):
                if record.extend_upwards < 0 or record.extend_downwards < 0:
                    raise UserError('请填写正确的延长时间！')

    """
    Onchange
    """

    @api.onchange('start_date', 'end_date')
    def onchange_start_end_date(self):
        if self.start_date and self.end_date:
            if (self.end_date - self.start_date).days < 0:
                raise UserError('请填写正确的时间！')
            else:
                if self.extend_upwards and self.extend_downwards:
                    self.update({'actual_begin_date': self.start_date - timedelta(days=self.extend_downwards),
                                 'actual_end_date': self.end_date + timedelta(days=self.extend_upwards)})

    @api.onchange('extend_upwards', 'extend_downwards')
    def onchange_extend_upwards_downwards(self):
        for record in self:
            if record.extend_upwards and record.extend_downwards:
                record.update({'actual_begin_date': record.start_date - timedelta(days=record.extend_downwards),
                               'actual_end_date': record.end_date + timedelta(days=record.extend_upwards)})
